import './main.css';
import zhini from './assent/zhini.mp3'

const audioEl: HTMLAudioElement = document.getElementById(
  'audio'
) as HTMLAudioElement
const cvs: HTMLCanvasElement = document.getElementById(
  'visual'
) as HTMLCanvasElement
const ctx = cvs.getContext('2d') as CanvasRenderingContext2D

function initCvs() {
  cvs.width = window.innerWidth * devicePixelRatio
  cvs.height = (window.innerHeight / 2) * devicePixelRatio
}

initCvs()

let isInit = false
let analyser: AnalyserNode | null = null
let dataArray: Uint8Array | null = null
audioEl.src = zhini
audioEl.onplay = () => {
  if (isInit) {
    return
  }
  isInit = true
  const audCtx = new AudioContext()
  const source = audCtx.createMediaElementSource(audioEl)
  analyser = audCtx.createAnalyser()
  analyser.fftSize = 512
  dataArray = new Uint8Array(analyser.frequencyBinCount)
  source.connect(analyser)
  analyser.connect(audCtx.destination)
}

function draw() {
  requestAnimationFrame(draw)
  const { width, height } = cvs
  ctx.clearRect(0, 0, width, height)
  if (!isInit) return
  ctx.fillStyle = '#78c5f7'

  analyser!.getByteFrequencyData(dataArray!)
  const barWidth = width / dataArray!.length
  for (let i = 0; i < dataArray!.length / 2; i++) {
    const barHeight = (dataArray![i] / 255) * height
    ctx.fillRect(
      i * barWidth + width / 2,
      height - barHeight,
      barWidth,
      barHeight
    )
    ctx.fillRect(
      width / 2 - (i + 1) * barWidth,
      height - barHeight,
      barWidth,
      barHeight
    )
  }
}

draw()
